<template>
  <view class="user-wrapper">
    <view class="user-header">
      <image class="header-bg" src="../../static/img/my/bg.png"></image>
      <view class="logo-wrap s-flex-r-s-c">
        <image class="logo" src="/static/img/my/logo.png"></image>
        <view class="name">港中盈</view>
      </view>
      <view class="user-logininfo" @click="skipMyInfo">
        <view class="user-left" v-if="userinfo && userinfo.id">
          <image class="avatar" :src="userinfo.avatar"></image>
          <view class="userinfo">
            <view class="name">{{ userinfo.nickname }}</view>
            <view class="phone">{{ userinfo.mobile }}</view>
          </view>
        </view>
        <view class="user-left" @click="handleLogin" v-else>
          <image class="avatar" src="../../static/img/my/avatar.png"></image>
          <text>登录/注册</text>
        </view>
        <view class="user-more" @click="skipMyInfo">
          <up-icon name="arrow-right" color="#fff" size="16"></up-icon>
          <!-- <image src="../../static/img/user/more.png"></image> -->
        </view>
      </view>
    </view>
    <view class="user-content">
      <view class="user-list">
<!--        <view class="user-item" @click="skipTracks">
          <view class="user-left">
            <image
              class="user-item-icon"
              src="../../static/img/my/Frame.png"></image>
            <text>我的足迹</text>
          </view>
          <view class="user-more">
            <image src="../../static/img/user/more.png"></image>
          </view>
        </view> -->
        <view class="user-item" @click="handleCollect">
          <view class="user-left">
            <image
              class="user-item-icon"
              src="../../static/img/my/Frame-1.png"></image>
            <text>我的收藏</text>
          </view>
          <view class="user-more">
            <image src="../../static/img/user/more.png"></image>
          </view>
        </view>
        <view class="user-item" @click="skipService">
          <view class="user-left">
            <image
              class="user-item-icon"
              src="../../static/img/my/Frame-2.png"></image>
            <text>我的服务</text>
          </view>
          <view class="user-more">
            <image src="../../static/img/user/more.png"></image>
          </view>
        </view>
        <view
          v-if="userinfo.user_type > 0"
          class="user-item"
          @click="skipAgent">
          <view class="user-left">
            <image
              class="user-item-icon"
              src="/static/img/my/Frame-3.png"></image>
            <text>{{ tab.menu }}</text>
          </view>
          <view class="user-more">
            <image src="../../static/img/user/more.png"></image>
          </view>
        </view>
      </view>
    </view>
<!--    <view class="user-adver">
      <image
        src="../../static/img/user/adver.png"
        @click="handleMakePhone"></image>
      <view class="mobile">
        {{ mobile }}
      </view>
    </view> -->
    <!-- 手机号快捷登录 -->
    <up-popup :round="10" :show="show" @close="close" @open="open">
      <view class="wrap padding-top-34">
        <image
          @click="close"
          class="close-img"
          src="/static/img/login/close.png"
          alt="" />
        <view class="logo s-flex-r-c-c">
          <image class="img" src="/static/img/login/title.png" alt="" />
        </view>
        <button class="btn s-flex-r-c-c" @click="wxhandleLogin">
          手机号登录
        </button>

        <view class="xieyi s-flex-r-c-c">
          <text>请勾选相关协议</text>
          <view class="jiao"></view>
        </view>
        <view class="t-xieyi s-flex-r-s-c">
          <image
            @click="checked = !checked"
            v-if="checked"
            class="icon circle"
            src="/static/img/login/yes.png"
            alt="" />
          <view @click="checked = !checked" v-else class="circle"></view>
          <view class="text">
            我已阅读并同意
            <text class="t">《用户协议》</text>
            与
            <text class="t">《隐私协议》</text>
          </view>
        </view>
        <!-- <view class="other-login s-flex-r-c-c">
          <view
            class="item s-flex-c-s-c"
            @click="go('/pages/login/login?loginType=1')">
            <image class="icon" src="/static/img/login/dun2.png" alt="" />
            <text>验证码登录</text>
          </view>
          <view
            class="item s-flex-c-s-c"
            @click="go('/pages/login/login?loginType=2')">
            <image class="icon" src="/static/img/login/account.png" alt="" />
            <text>账号密码登录</text>
          </view>
        </view> -->
      </view>
    </up-popup>
    <!-- 获取验证码 -->
    <up-popup :show="errcord" @close="close3" @open="open3" :round="10">
      <view
        class="wrap padding-top-34"
        style="height: 284px; padding-top: 100px">
        <image
          @click="close3"
          class="close-img"
          src="/static/img/login/close.png"
          alt="" />
        <view class="logo s-flex-r-c-c">
          <image class="img" src="/static/img/login/title.png" alt="" />
        </view>
        <button
          class="btn s-flex-r-c-c"
          open-type="getPhoneNumber"
          @getphonenumber="getUserPhone">
          手机号快捷登录
        </button>
      </view>
    </up-popup>
    <up-popup :show="show2" @close="close2" @open="open2">
      <view class="wrap2 padding-top-54">
        <image
          @click="close2"
          class="close-img"
          src="/static/img/login/close.png"
          alt="" />
        <view class="title">填写手机短信验证码</view>
        <view class="toast s-flex-r-b-c padding-lr-50">
          <view class="left">
            已发送至{{ phoneNumber.slice(0, 3) }}****{{
              phoneNumber.slice(7, 12)
            }}
          </view>
          <view class="send" @click="sendCode">{{ getCode }}</view>
        </view>
        <view class="code-box s-flex-c-c-c">
          <up-code-input
            class="code"
            @change="change2"
            v-model="value"
            @finish="finish"
            disabled-keyboard
            borderColor="#6DDA47"
            :maxlength="4"></up-code-input>
        </view>
        <view class="code-box s-flex-c-c-c">
          <u-number-keyboard
            @backspace="backspace"
            @change="change"
            mode="number"
            :dotDisabled="false"></u-number-keyboard>
        </view>
      </view>
    </up-popup>
  </view>
</template>
<script setup>
import { ref, getCurrentInstance, reactive } from "vue";
import { onShow } from "@dcloudio/uni-app";
const { proxy } = getCurrentInstance();
const checked = ref(false);
const timerFlag = ref(false);
const loginType = ref(1);
// 手机号快捷登录
const show = ref(false);
const phoneNumber = ref("");
const mobile = ref("");
const tab = ref({});
const userinfo = ref(uni.getStorageSync("userinfo"));
const sharePath = ref(uni.getStorageSync('sharePath'));
const access_token = ref("");
const value = ref("");
const newToken = ref("");
const wxLoginForm = ref({
  code: "",
  encryptedIv: "",
  encryptedData: "",
});
const errcord = ref(false);
onShow(() => {
  getUserData();
});
function getUserData() {
  proxy
    .$request({
      url: "api/User/getUserInfo",
      header: "application/x-www-form-urlencoded",
      data: {},
    })
    .then((res) => {
      if (res.code == 0) {
        return proxy.$toast(res.msg);
      } else if (res.code == 401) {
        show.value = true;
        uni.removeStorageSync("token");
        uni.removeStorageSync("userinfo");
      } else {
        userinfo.value = res.data;
        if (res.data.user_type > 0) getUserMenu();
      }
    });
  // 客服热线
  proxy
    .$request({
      url: "api/User/getAboutPhone",
      header: "application/x-www-form-urlencoded",
      data: {},
    })
    .then((res) => {
      if (res.code == 0) {
        return proxy.$toast(res.msg);
      } else {
        mobile.value = res.data.phone_number;
      }
    });
}
function getUserMenu() {
  proxy
    .$request({
      url: "api/User/getUserMenu",
      header: "application/x-www-form-urlencoded",
      data: {},
    })
    .then((res) => {
      if (res.code == 0) {
        return proxy.$toast(res.msg);
      } else {
        tab.value = res.data;
      }
    });
}

const handleLogin = () => {
  show.value = true;
};
const close = () => {
  show.value = false;
};
const open = () => {
  show.value = true;
};
const close3 = () => {
  errcord.value = false;
};
const open3 = () => {
  errcord.value = true;
};
// 获取验证码
const show2 = ref(false);
const close2 = () => {
  show2.value = false;
};
const open2 = () => {
  show2.value = true;
};

const getCode = ref("发送验证码");
function sendCode() {
  if (!/[0-9]{11}/.test(phoneNumber.value)) {
    uni.showToast({
      icon: "none",
      title: "请输入正确的手机号",
    });
    return;
  }
  if (timerFlag.value === false) {
    proxy
      .$request({
        url: "api/sms/send",
        header: "application/x-www-form-urlencoded",
        data: {
          mobile: phoneNumber.value,
          event: "mobilelogin",
        },
      })
      .then((res) => {
        if (res.code == 0) {
          return proxy.$toast(res.msg);
        } else {
          timerFlag.value = !timerFlag.value;
          uni.showToast({
            icon: "none",
            title: res.msg,
          });
          countDown(60);
        }
      });
  }
}
function countDown(time) {
  let count = time;
  setTimeout(() => {
    count--;
    if (time <= 0) {
      getCode.value = "获取验证码";
      timerFlag.value = false;
    } else if (count !== time) {
      getCode.value = "重新获取" + count;
      countDown(count);
    }
  }, 1000);
}
function getUserPhone(e) {
  // 获取到回调信息，需要code(与登录login的code不同)
  console.log("回调返回的信息：", e);
  if (!checked.value) {
    return proxy.$toast("请勾选协议继续");
  }
  proxy
    .$request({
      url: "/api/user/getAccessToken",
      header: "application/x-www-form-urlencoded",
      data: {
        code: wxLoginForm.value.code,
        platform: "wechat",
      },
    })
    .then((res) => {
      console.log("res2222: ", res);
      if (res.code == 0) {
        return proxy.$toast(res.msg);
      } else if (res.code == 1) {
        access_token.value = res.data.access_token;
        console.log("access_token.value: ", access_token.value);
        getPhone(e.detail.code);
      } else {
        return proxy.$toast(res.msg);
      }
    })
    .catch(() => {
      console.log("登录失败");
    });
}
function getPhone(code) {
  console.log(newToken.value, 3234234);
  proxy
    .$request({
      url: "/api/user/getuserphonenumber",
      header: "application/x-www-form-urlencoded",

      data: {
        access_token: access_token.value,
        code: code,
        openid: newToken.value,
      },
    })
    .then((res) => {
      if (res.code == 0) {
        return proxy.$toast(res.msg);
      } else if (res.code == 1) {
        // phoneNumber.value = res.data.phone_info.phoneNumber;
        show.value = false;
        // sendCode();
        errcord.value = false;
        uni.setStorageSync("token", res.data.userinfo.token);
        uni.switchTab({
          url: "/pages/index/index",
        });
      }
    })
    .catch(() => {
      console.log("登录失败");
    });
  return false;
}
// 键盘
// 退格键
function backspace() {
  // 删除value的最后一个字符
  if (value.value.length) {
    value.value = value.value.substr(0, value.value.length - 1);
  }
  console.log(value.value);
}
function change(val) {
  if (value.value.length < 4) {
    value.value += val;
  }
  if (value.value.length == 4) {
    finish(value.value);
  }
}
const change2 = (e) => {
  console.log("change2e: ", e);
};
const finish = (e) => {
  console.log("e: ", e);
  proxy
    .$request({
      url: "api/user/mobilelogin",
      header: "application/x-www-form-urlencoded",
      data: {
        mobile: phoneNumber.value,
        captcha: e,
      },
    })
    .then((res) => {
      console.log(res, 888);
      if (res.code == 1) {
        return proxy.$toast(res.msg);
      } else {
        // token
        show2.value = false;
        proxy.$toast("登录成功");
        uni.setStorageSync("token", res.data.userinfo.token);
        uni.setStorageSync("userinfo", res.data.userinfo);

        uni.reLaunch({
          url: "/pages/index/index",
        });
      }
    });
};
//我的服务
function skipService() {
  uni.navigateTo({
    url: "/pages/my/service/index",
  });
}
function handleMakePhone() {
  uni.makePhoneCall({
    phoneNumber: mobile.value,
  });
}
//我的资料
function skipMyInfo() {
  uni.navigateTo({
    url: "/pages/my/editInfo",
  });
}
function skipTracks() {
  uni.navigateTo({
    url: "/pages/my/tracks",
  });
}
function skipAgent() {
  uni.navigateTo({
    url: "/pages/my/agent",
  });
}
function handleCollect() {
  uni.navigateTo({
    url: "/pages/my/collection",
  });
}
/**微信授权登录**/
function wxhandleLogin() {
	if(!checked.value){
		return proxy.$toast("请先同意协议");
	}
  uni.getProvider({
    service: "oauth",
    success: (res) => {
      if (res.provider.some((i) => i == "weixin")) {
        uni.login({
          provider: "weixin",
          success: (loginRes) => {
            console.log(loginRes, 23233);
            wxLoginForm.value.code = loginRes.code;
            uni.getUserInfo({
              success: (res2) => {
                wxLoginForm.value.iv = res2.iv;
                wxLoginForm.value.encryptedData = res2.encryptedData;
                sendWxLoginFormToLocalService();
              },
            });
          },
          fail: (err) => {
            console.log("err: ", err);
          },
        });
      }
    },
  });
}
function sendWxLoginFormToLocalService() {
  uni.showLoading({
    title: "加载中",
  });
  proxy
    .$request({
      url: "/api/user/thirdCode",
      header: "application/x-www-form-urlencoded",
      data: {
        code: wxLoginForm.value.code,
        platform: "wechat",
        sourceUserId: uni.getStorageSync("sourceUserId")
          ? uni.getStorageSync("sourceUserId")
          : "",
      },
    })
    .then((res) => {
      uni.hideLoading();
      if (res.code == 405) {
        show3.value = true;
        access_token.value = res.data.access_token;
      } else if (res.code == 1) {
        if (res.data.userinfo.mobile == "") {
          errcord.value = true;
          newToken.value = res.data.openid;
          // uni.setStorageSync("token", res.data.userinfo.token);
        } else {
          errcord.value = false;
		  const path = uni.getStorageSync('sharePath')
          proxy.$toast("登录成功");
		  // 有分享地址跳转分享地址
		  if(path ){
			  const tabPaths=[
				  'pages/index/index',
				  "pages/zixun/zixun",
				  "pages/my/index",
			  ]
			  if(tabPaths.includes(path)){
				  uni.switchTab({
					url:'/'+path,
				  })
			  }else{
				  proxy.$toast(path);
				  proxy.go('/'+path)
			  }
			  uni.clearStorageSync('sharePath');
		  }
          show.value = false;
          uni.setStorageSync("token", res.data.userinfo.token);
          uni.setStorageSync("userinfo", res.data.userinfo);
          getUserData();
        }
      } else {
        // 没有注册就重新获取手机号
        errcord.value = true;
        access_token.value = res.data.access_token;
        newToken.value = res.data.openid;
        console.log(33333);
        return;
      }
    })
    .catch(() => {
      console.log("登录失败");
    });
}
function sendWxLoginFormToLocalService2() {
  proxy
    .$request({
      url: "/api/user/third",
      header: "application/x-www-form-urlencoded",
      data: {
        code: wxLoginForm.value.code,
        mobile: userPhone.value,
        iv: wxLoginForm.value.iv,
        encryptedData: wxLoginForm.value.encryptedData,
        platform: "wechat",
      },
    })
    .then((res) => {
      if (res.code == 0) {
        return proxy.$toast(res.msg);
      } else {
        proxy.$toast("登录成功");
        uni.setStorageSync("token", res.data.userinfo.token);
        uni.setStorageSync("userinfo", res.data.userinfo);
        uni.reLaunch({
          url: "/pages/index/index",
        });
      }
    })
    .catch(() => {
      console.log("登录失败");
    });
}
</script>
<style lang="scss" scoped>
.user-wrapper {
  .btn {
    margin: 0 auto;
    width: 686rpx;
    height: 108rpx;
    background: linear-gradient(128deg, #ff9839 0%, #ff7139 100%);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    font-weight: 800;
    font-size: 32rpx;
    color: #ffffff;
    line-height: 60rpx;
  }
  .user-header {
    position: relative;
    image {
      width: 100%;
      height: 390rpx;
    }
    .logo-wrap {
      position: absolute;
      top: 100rpx;
      left: 32rpx;
      .logo {
        background: #ffffff;
        width: 40rpx;
        height: 40rpx;
        margin-right: 12rpx;
        border-radius: 50rpx;
      }
      .name {
        font-weight: 500;
        font-size: 28rpx;
        color: #ffffff;
        line-height: 33rpx;
      }
    }
    // background-color: #FF7139;
  }

  .user-logininfo {
    position: absolute;
    top: 186rpx;
    display: flex;
    align-items: center;
    width: 680rpx;
    padding: 0 32rpx;
    justify-content: space-between;

    .user-left {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .avatar {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50rpx;
        margin-right: 20rpx;
        position: relative;
        top: 3rpx;
      }
      .userinfo {
        .name {
          font-weight: 500;
          font-size: 28rpx;
          color: #ffffff;
          line-height: 40rpx;
        }
        .phone {
          margin-top: 6rpx;
          font-size: 24rpx;
          color: #ffffff;
          line-height: 40rpx;
        }
      }
      color: #fff;
    }

    .user-more {
      image {
        width: 28rpx;
        height: 28rpx;
      }
    }
  }

  .user-content {
    .user-list {
      .user-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 108rpx;
        line-height: 108rpx;
        padding: 0 34rpx;
        border-bottom: 4rpx solid #f8f8f8;
      }

      .user-left {
        image {
          width: 30rpx;
          height: 30rpx;
          margin-right: 10rpx;
          position: relative;
          top: 3rpx;
        }
      }

      .user-more {
        image {
          width: 28rpx;
          height: 28rpx;
        }
      }
    }
  }

  .user-adver {
    text-align: center;
    position: relative;
    padding: 32rpx auto;
    .mobile {
      position: absolute;
      top: 92rpx;
      left: 61rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #f95945;
      line-height: 44rpx;
    }
    image {
      width: 686rpx;
      height: 158rpx;
    }
  }
}
.wrap {
  padding-top: 34rpx;
  padding-bottom: 24rpx;
  position: relative;
  .close-img {
    position: absolute;
    right: 32rpx;
    top: 32rpx;
    width: 32rpx;
    height: 32rpx;
  }
  .logo {
    margin: 0 auto;
    width: 148rpx;
    height: 148rpx;
    background: #ffffff;
    border-radius: 74rpx;
    border: 2rpx solid #cc5610;
    margin-bottom: 64rpx;
    .img {
      width: 122rpx;
      height: 64rpx;
    }
  }
  .btn {
    margin: 0 auto;
    width: 686rpx;
    height: 108rpx;
    background: linear-gradient(128deg, #ff9839 0%, #ff7139 100%);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    font-weight: 800;
    font-size: 32rpx;
    color: #ffffff;
    line-height: 60rpx;
  }
  .xieyi {
    margin-left: 34rpx;
    margin-top: 72rpx;
    width: 204rpx;
    height: 44rpx;
    background: #fff1eb;
    border-radius: 22rpx 22rpx 22rpx 22rpx;
    font-weight: 400;
    font-size: 24rpx;
    color: #ff7139;
    line-height: 28rpx;
    position: relative;
    .jiao {
      position: absolute;
      bottom: -10rpx;
      left: 16rpx;
      width: 16rpx;
      height: 16rpx;
      background: #fff1eb;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
      transform: rotate(45deg);
    }
  }
  .t-xieyi {
    margin-left: 34rpx;
    margin-top: 28rpx;
    .circle {
      width: 40rpx;
      height: 40rpx;
      border-radius: 20rpx;
      border: 2rpx solid #999999;
      margin-right: 16rpx;
      box-sizing: border-box;
    }
    .icon {
      border: none;
    }
    .text {
      font-weight: 400;
      font-size: 28rpx;
      color: #666666;
      line-height: 33rpx;
      text-align: left;
      .t {
        color: #ff7139;
      }
    }
  }
  .other-login {
    margin-top: 66rpx;
    .item {
      flex: 1;
    }
    .icon {
      width: 100rpx;
      height: 100rpx;
      margin-bottom: 28rpx;
    }
    font-weight: 400;
    font-size: 28rpx;
    color: #333333;
    line-height: 33rpx;
  }
}
.wrap2 {
  padding-top: 54rpx;
  padding-bottom: 24rpx;
  position: relative;
  .close-img {
    position: absolute;
    left: 32rpx;
    top: 52rpx;
    width: 32rpx;
    height: 32rpx;
  }
  .title {
    font-weight: 500;
    font-size: 32rpx;
    color: #333333;
    // line-height: 76rpx;
    text-align: center;
    margin-bottom: 30rpx;
  }
  .toast {
    font-weight: 400;
    font-size: 28rpx;
    color: #999999;
    line-height: 76rpx;
  }
  .code-box {
    margin-top: 30rpx;
  }
}
</style>
